/**
 *
 * Description: 
 *
 * @author lirong
 * @version 1.0
 * <pre>
 * Modification History: 
 * Date         Author      Version     Description 
 * ------------------------------------------------------------------ 
 * 2012-3-15    lirong       1.0        1.0 Version 
 * </pre>
 */

package com.creditease.rss.ui;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebView.HitTestResult;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.creditease.rss.RssConst;
import com.creditease.rss.dao.RssItemDB;
import com.creditease.rss.model.RssItemModel;
import com.creditease.rss.util.CacheMgr;
import com.creditease.rss.util.FileUtil;
import com.creditease.rss.util.StreamUtil;

/**
 * 
 * Description:
 * 
 * @author lirong
 * @version 1.0
 * 
 *          <pre>
 * Modification History: 
 * Date         Author      Version     Description 
 * ------------------------------------------------------------------ 
 * 2012-3-15    lirong       1.0        1.0 Version
 * </pre>
 */

public class RssReader extends Activity {
	private String link;
	private TextView titleText;
	private String title;
	private RssItemDB db;
	private final String TAG = RssReader.class.getName();
	private ImageView titleView;
	private ImageView reflushView;
	private ProgressBar processbar;
	private String[] pics;
	private String rssTitle;
	private ViewFlipper flipper;

	private GestureDetector detector;
	private int rssItemIndex = 0;
	private List<RssItemModel> beans;
	private View convertView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.rss_reader_flip);
		detector = new GestureDetector(new MySimpleGesture());
		flipper = (ViewFlipper) this.findViewById(R.id.ViewFlipper01);

		Intent intent = getIntent();
		link = intent.getExtras().getString("link");
		title = intent.getExtras().getString("title");
		String id = intent.getExtras().getString("id");
		String sectionId = intent.getExtras().getString("sectionId");
		db = new RssItemDB(getApplicationContext());
		// List<RssItemModel> items = CacheMgr.getList(sectionId);
		Log.d(TAG, "id=" + id);
		beans = CacheMgr.get(sectionId);// db.findById(id);

		int i = 0;
		boolean breakIndex = false;
		for (RssItemModel bean : beans) {
			TextView view = getSubView(bean, i);
			flipper.addView(view, i);
			if (id.equals(bean.id)) {
				breakIndex = true;
			}
			if (!breakIndex) {
				rssItemIndex++;
			}
			i++;
		}
		Log.d(TAG, "flipper view count=" + flipper.getChildCount());
		setIndex(rssItemIndex);
		flipper.setDisplayedChild(rssItemIndex);
		// flipper.showNext();
	}

	private TextView getSubView(final RssItemModel bean, int i) {

		TextView tView = new TextView(getApplicationContext());
		tView.setText(i + "  Loading...");
		return tView;
	}

	/**
	 * Description:
	 * 
	 * @param
	 * @return StringBuilder
	 * @throws
	 * @Author liong Create Date: 2012-5-10 下午5:45:44
	 */

	private StringBuilder getContent(final RssItemModel bean) {
		StringBuilder buf = new StringBuilder();

		InputStream fisFileInputStream = null;
		try {
			rssTitle = bean.articleTitle;
			fisFileInputStream = getApplication().getAssets().open(
					"templete.html");
			String tempString = StreamUtil.stream2String(fisFileInputStream);

			tempString = tempString.replace("{ARTICLE_TITLE}",
					bean.articleTitle);
			tempString = tempString.replace("{SECTION_NAME}",
					bean.articleAuthorName == null
							? ""
							: bean.articleAuthorName);
			tempString = tempString.replace("{ARTICLE_URL}",
					"http://gate.baidu.com/tc?from=opentc&src="
							+ bean.articleLink);
			tempString = tempString.replace("{ARTICLE_DATE}",
					new SimpleDateFormat("MM月dd日 HH:mm")
							.format(bean.articleTime));
			String contentString = bean.content;
			if (contentString == null || contentString.trim().length() == 0) {
				contentString = "<div class='content-loading'>抱歉，加载内容失败。</div>";
			} else {
				Document document = Jsoup.parse(contentString);
				document.select("a").removeAttr("target").removeAttr("href");
				document.select("span").removeAttr("style");
				Elements imgs = document.select("img[src]");
				if (imgs != null && imgs.size() > 0) {
					List<String> list = new ArrayList<String>();
					for (Element ele : imgs) {
						String imgurl = ele.attr("src");
						String newFileName = FileUtil.getFileName(imgurl);
						String path = RssConst.PIC_TMP_DIR + newFileName;
						File file = new File(path);
						if (file.exists()) {
							list.add(path);
							ele.attr("src", RssConst.FILE_PREFIX + path);
						} else {
							list.add(imgurl);
							// PicDownloadUtil.add2Queue(imgurl, path);
						}
					}
					pics = list.toArray(new String[list.size()]);
					contentString = document.toString();
				}
			}
			tempString = tempString.replace("{ARTICLE_CONTENT}", contentString);
			buf.append(tempString);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fisFileInputStream != null) {
				try {
					fisFileInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return buf;
	}
	private void setIndex(int index) {
		Log.d(TAG, "show index=" + index);
		convertView = LayoutInflater.from(getApplicationContext()).inflate(
				R.layout.rss_reader, null);
		// 设置Home图标
		titleView = (ImageView) convertView.findViewById(R.id.titleIcon);
		Drawable drawable = getResources().getDrawable(R.drawable.icon_back);
		titleView.setAdjustViewBounds(true);
		titleView.setImageDrawable(drawable);
		titleView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				RssReader.this.onBackPressed();
			}
		});
		// 标题
		titleText = (TextView) convertView.findViewById(R.id.titleText);
		titleText.setText(title);

		processbar = (ProgressBar) convertView
				.findViewById(R.id.progressbar_updown);
		// 刷新按钮不可见
		reflushView = (ImageView) convertView.findViewById(R.id.reflushIcon);
		reflushView.setAdjustViewBounds(true);
		reflushView.setBackgroundResource(R.drawable.listview_selector);

		final RssItemModel bean = beans.get(index);
		if (bean.isFav) {
			Drawable drawable1 = getResources().getDrawable(
					R.drawable.menu_favorite);
			reflushView.setImageDrawable(drawable1);

		} else {
			Drawable drawable1 = getResources().getDrawable(
					R.drawable.menu_favorite_cancel);
			reflushView.setImageDrawable(drawable1);
		}
		reflushView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				bean.isFav = !bean.isFav;
				bean.favTime = new Date().getTime();
				db.update(bean);
				if (bean.isFav) {
					Drawable drawable1 = getResources().getDrawable(
							R.drawable.menu_favorite);
					reflushView.setImageDrawable(drawable1);
					Toast.makeText(getApplicationContext(), R.string.favOK,
							Toast.LENGTH_SHORT).show();
				} else {
					Drawable drawable1 = getResources().getDrawable(
							R.drawable.menu_favorite_cancel);
					reflushView.setImageDrawable(drawable1);
					Toast.makeText(getApplicationContext(), R.string.favCannel,
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		StringBuilder buf = getContent(bean);
		WebView webView = getWebView();

		webView.setOnTouchListener(new OnTouchListener() {
			private boolean flag = false;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					flag = true;
				} else if (flag && event.getAction() == MotionEvent.ACTION_UP) {
					HitTestResult result = ((WebView) v).getHitTestResult();
					int resultType = result.getType();
					if (resultType == HitTestResult.IMAGE_TYPE) {
						Intent intent = new Intent();
						intent.setClass(getApplicationContext(),
								ImageSwitcherActivity.class);
						intent.putExtra("list", pics);
						intent.putExtra("rssTitle", rssTitle);
						int index = 0;
						int len = RssConst.FILE_PREFIX.length();
						String extra = result.getExtra();
						String extraStr = "";
						if (extra.startsWith("http")) {
							extraStr = extra;
						} else {
							extraStr = extra.substring(len);
						}
						Log.d(TAG, "extra=" + extraStr);
						Log.d(TAG, "pics size=" + pics.length);
						for (String picUrl : pics) {
							if (extraStr.equals(picUrl)) {
								break;
							}
							index++;
						}
						if (index >= pics.length) {
							Toast.makeText(getApplicationContext(), "图片不能正常浏览",
									Toast.LENGTH_SHORT).show();
						} else {
							intent.putExtra("index", index);
							startActivity(intent);
						}
					}
					flag = false;
				} else {
					flag = false;
				}
				return false;
			}
		});
		webView.loadDataWithBaseURL(null, buf.toString(), "text/html", "UTF-8",
				null);
		TextView tView = (TextView) flipper.getChildAt(index);
		flipper.removeView(tView);
		flipper.addView(webView, index);
		// flipper.setDisplayedChild(index);
	}

	private WebView myWebView = null;
	/**
	 * Description:
	 * 
	 * @param
	 * @return WebView
	 * @throws
	 * @Author liong Create Date: 2012-5-11 下午12:49:19
	 */

	private WebView getWebView() {
		if (myWebView == null) {
			WebView webView = new WebView(this);//(WebView) convertView.findViewById(R.id.webView);
			webView.getSettings().setJavaScriptEnabled(true);
			// 支持缩放
			webView.getSettings().setBuiltInZoomControls(true);
			webView.getSettings().setLayoutAlgorithm(
					WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
			// 使页面获得焦点
			webView.requestFocus();
			WebSettings ws = webView.getSettings();
			// 首先从cache加载，如果cache不存在则从网络加载
			ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
			ws.setAppCacheEnabled(true);
			ws.setPluginsEnabled(true);

			ws.setAppCacheMaxSize(50 * 1024 * 1024);
			ws.setAllowFileAccess(true);
			ws.setAppCachePath(RssConst.APPROOT);
			ws.setDatabaseEnabled(true);
			ws.setDatabasePath(RssConst.APPROOT);
			// ws.setLightTouchEnabled(true);
			webView.setWebViewClient(new RssWebViewClient());
			webView.setWebChromeClient(new WebChromeClient() {
				@Override
				public void onProgressChanged(WebView view, int newProgress) {
					// super.onProgressChanged(view, newProgress);
					processbar.setProgress(newProgress);
					if (newProgress == 100) {
						processbar.setVisibility(View.GONE);
					}
				}
			});
			webView.getSettings().setDefaultTextEncodingName("UTF-8");
			myWebView = webView;
		}
		return myWebView;
	}

	public void openDetailPage(View view) {
		Intent intent = new Intent();
		intent.setClass(getApplicationContext(), RssReaderDetail.class);
		intent.putExtra("url", link);
		intent.putExtra("title", title);
		startActivity(intent);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		this.detector.onTouchEvent(event);
		return true;
	}

	private class MySimpleGesture extends SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			Log.d(TAG, "onFling................................");
			if (e1.getX() - e2.getX() > 120) {
				Log.d(TAG, "onFling show next");
				flipper.setInAnimation(AnimationUtils.loadAnimation(
						getApplicationContext(), R.anim.push_left_in));
				flipper.setOutAnimation(AnimationUtils.loadAnimation(
						getApplicationContext(), R.anim.push_left_out));
				rssItemIndex++;
				setIndex(rssItemIndex);
				flipper.showNext();
				return true;
			} else if (e2.getX() - e1.getX() > 120) {
				Log.d(TAG, "onFling show previous");
				flipper.setInAnimation(AnimationUtils.loadAnimation(
						getApplicationContext(), R.anim.push_right_in));
				flipper.setOutAnimation(AnimationUtils.loadAnimation(
						getApplicationContext(), R.anim.push_right_out));
				rssItemIndex--;
				setIndex(rssItemIndex);
				flipper.showPrevious();
				return true;
			}
			return false;
		}
	}

	private class RssWebViewClient extends WebViewClient {
		// 在点击请求的是链接是才会调用，重写此方法返回true表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边。
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			processbar.setVisibility(View.VISIBLE);
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			// TextView tv = (TextView) findViewById(R.id.loadingMsg);
			// tv.setVisibility(View.GONE);
			super.onPageFinished(view, url);
		}

		// 在加载页面资源时会调用，每一个资源（比如图片）的加载都会调用一次。
		@Override
		public void onLoadResource(WebView view, String url) {
			// Log.d(TAG, "URL=" + url);
			super.onLoadResource(view,
					"http://gate.baidu.com/tc?from=opentc&src=" + url);
		}

		@Override
		public void onTooManyRedirects(WebView view, Message cancelMsg,
				Message continueMsg) {
			super.onTooManyRedirects(view, cancelMsg, continueMsg);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
		}

		@Override
		public void onFormResubmission(WebView view, Message dontResend,
				Message resend) {
			super.onFormResubmission(view, dontResend, resend);
		}

		@Override
		public void doUpdateVisitedHistory(WebView view, String url,
				boolean isReload) {
			super.doUpdateVisitedHistory(view, url, isReload);
		}

		@Override
		public void onReceivedSslError(WebView view, SslErrorHandler handler,
				SslError error) {
			super.onReceivedSslError(view, handler, error);
		}

		@Override
		public void onReceivedHttpAuthRequest(WebView view,
				HttpAuthHandler handler, String host, String realm) {
			super.onReceivedHttpAuthRequest(view, handler, host, realm);
		}

		@Override
		public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
			return super.shouldOverrideKeyEvent(view, event);
		}

		@Override
		public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
			super.onUnhandledKeyEvent(view, event);
		}

		@Override
		public void onScaleChanged(WebView view, float oldScale, float newScale) {
			super.onScaleChanged(view, oldScale, newScale);
		}
	}
}
